package com.beantools.reflect.enums;

import com.alibaba.fastjson.JSONObject;
import com.beantools.execption.PropertyException;
import com.beantools.util.valid.Validate;
import com.beantools.util.valid.ValidateFactory;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created By zby on 18:19 2019/7/19
 */

public abstract class AbstractsEnumJson implements Serializable{

    private static final long serialVersionUID = -8307551925580064988L;


    protected static boolean checked(JSONObject json, String[] fieldNames, Class clazz) throws PropertyException {
        Validate.validate(new ValidateFactory() {
            @Override
            public boolean validate(Object... objects) {
                for (String fieldName : fieldNames) {
                    boolean flag = false;
                    if (json.containsKey(fieldName)) {
                        flag = true;
                    }
                    if (!flag) {
                        throw new PropertyException("没有该属性", fieldName, clazz);
                    }
                }
                return true;
            }
        }, fieldNames, json, clazz);
        return true;
    }

    /**
     * 检查用户输入的属性是否在当前对象的属性中，如果不在，则抛出异常，否则，则<code>json</code>
     * 对象中只保留用户输入的字段。
     *
     * @param json       json对象
     * @param fieldNames 属性集合
     * @param aClass     当前类对象
     */
    protected static void checkRemoveKey(JSONObject json, String[] fieldNames, Class<?> aClass) {
        boolean checked = checked(json, fieldNames, aClass);
        if (checked) {
            boolean notExist = true;
            Set<Map.Entry<String, Object>> set = json.entrySet();
            Iterator<Map.Entry<String, Object>> iterator = set.iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = iterator.next();
                String key = (String) entry.getKey();
                if (key.equals("key")) {
                    continue;
                }
                for (String fieldName : fieldNames) {
                    if (json.containsKey(fieldName)) {
                        notExist = !notExist;
                        break;
                    }
                }
                if (notExist) {
                    iterator.remove();
                }
            }
        }
    }
}
